from fastapi import APIRouter, Depends, HTTPException, status, Query
from sqlalchemy.orm import Session
from sqlalchemy import or_
from typing import Optional
from config.database import get_db
from models import User, Book, RoleType
from schemas import (
    ResponseModel, UserResponse, UserCreate, BookResponse, BookCreate, 
    BookListResponse, PaginationParams
)
from auth import get_current_admin_user, get_password_hash
import math

router = APIRouter()

# 用户管理
@router.get("/users", response_model=ResponseModel)
async def get_users(
    page: int = Query(1, ge=1, description="页码"),
    page_size: int = Query(10, ge=1, le=100, description="每页数量"),
    keyword: Optional[str] = Query(None, description="搜索关键词"),
    current_admin: User = Depends(get_current_admin_user),
    db: Session = Depends(get_db)
):
    """获取用户列表"""
    # 构建查询
    query = db.query(User)
    
    # 如果有关键词，进行模糊搜索
    if keyword:
        search_filter = or_(
            User.username.contains(keyword),
            User.real_name.contains(keyword),
            User.phone.contains(keyword),
            User.student_id.contains(keyword)
        )
        query = query.filter(search_filter)
    
    # 计算总数
    total = query.count()
    
    # 分页
    offset = (page - 1) * page_size
    users = query.offset(offset).limit(page_size).all()
    
    # 转换为响应模型
    user_responses = [UserResponse.from_orm(user) for user in users]
    
    # 计算总页数
    total_pages = math.ceil(total / page_size)
    
    # 构造响应
    response_data = {
        "users": user_responses,
        "total": total,
        "page": page,
        "page_size": page_size,
        "total_pages": total_pages
    }
    
    return ResponseModel(
        code=200,
        message="获取用户列表成功",
        data=response_data
    )

@router.post("/users", response_model=ResponseModel)
async def create_user(
    user_create: UserCreate,
    current_admin: User = Depends(get_current_admin_user),
    db: Session = Depends(get_db)
):
    """创建用户"""
    # 检查用户名是否已存在
    existing_user = db.query(User).filter(User.username == user_create.username).first()
    if existing_user:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="用户名已存在"
        )
    
    # 检查密码确认
    if user_create.password != user_create.confirm_password:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="密码确认不匹配"
        )
    
    # 创建用户
    db_user = User(
        username=user_create.username,
        password=get_password_hash(user_create.password),
        real_name=user_create.real_name,
        phone=user_create.phone,
        student_id=user_create.student_id,
        contact_info=user_create.contact_info,
        role_type=user_create.role_type
    )
    
    db.add(db_user)
    db.commit()
    db.refresh(db_user)
    
    user_response = UserResponse.from_orm(db_user)
    
    return ResponseModel(
        code=200,
        message="创建用户成功",
        data=user_response
    )

@router.put("/users/{user_id}", response_model=ResponseModel)
async def update_user(
    user_id: int,
    user_update: UserCreate,
    current_admin: User = Depends(get_current_admin_user),
    db: Session = Depends(get_db)
):
    """更新用户"""
    # 查找用户
    db_user = db.query(User).filter(User.id == user_id).first()
    if not db_user:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="用户不存在"
        )
    
    # 检查用户名是否已被其他用户使用
    existing_user = db.query(User).filter(
        User.username == user_update.username,
        User.id != user_id
    ).first()
    if existing_user:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="用户名已存在"
        )
    
    # 检查密码确认
    if user_update.password != user_update.confirm_password:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="密码确认不匹配"
        )
    
    # 更新用户信息
    db_user.username = user_update.username
    db_user.password = get_password_hash(user_update.password)
    db_user.real_name = user_update.real_name
    db_user.phone = user_update.phone
    db_user.student_id = user_update.student_id
    db_user.contact_info = user_update.contact_info
    db_user.role_type = user_update.role_type
    
    db.commit()
    db.refresh(db_user)
    
    user_response = UserResponse.from_orm(db_user)
    
    return ResponseModel(
        code=200,
        message="更新用户成功",
        data=user_response
    )

@router.delete("/users/{user_id}", response_model=ResponseModel)
async def delete_user(
    user_id: int,
    current_admin: User = Depends(get_current_admin_user),
    db: Session = Depends(get_db)
):
    """删除用户"""
    # 查找用户
    db_user = db.query(User).filter(User.id == user_id).first()
    if not db_user:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="用户不存在"
        )
    
    # 不能删除自己
    if db_user.id == current_admin.id:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="不能删除自己"
        )
    
    # 删除用户
    db.delete(db_user)
    db.commit()
    
    return ResponseModel(
        code=200,
        message="删除用户成功"
    )

# 图书管理
@router.get("/books", response_model=ResponseModel)
async def get_books(
    page: int = Query(1, ge=1, description="页码"),
    page_size: int = Query(10, ge=1, le=100, description="每页数量"),
    keyword: Optional[str] = Query(None, description="搜索关键词"),
    current_admin: User = Depends(get_current_admin_user),
    db: Session = Depends(get_db)
):
    """获取图书列表"""
    # 构建查询
    query = db.query(Book)
    
    # 如果有关键词，进行模糊搜索
    if keyword:
        search_filter = or_(
            Book.title.contains(keyword),
            Book.author.contains(keyword),
            Book.publisher.contains(keyword),
            Book.isbn.contains(keyword)
        )
        query = query.filter(search_filter)
    
    # 计算总数
    total = query.count()
    
    # 分页
    offset = (page - 1) * page_size
    books = query.offset(offset).limit(page_size).all()
    
    # 转换为响应模型
    book_responses = [BookResponse.from_orm(book) for book in books]
    
    # 计算总页数
    total_pages = math.ceil(total / page_size)
    
    # 构造响应
    book_list_response = BookListResponse(
        books=book_responses,
        total=total,
        page=page,
        page_size=page_size,
        total_pages=total_pages
    )
    
    return ResponseModel(
        code=200,
        message="获取图书列表成功",
        data=book_list_response
    )

@router.post("/books", response_model=ResponseModel)
async def create_book(
    book_create: BookCreate,
    current_admin: User = Depends(get_current_admin_user),
    db: Session = Depends(get_db)
):
    """创建图书"""
    # 检查ISBN是否已存在
    existing_book = db.query(Book).filter(Book.isbn == book_create.isbn).first()
    if existing_book:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="ISBN已存在"
        )
    
    # 创建图书
    db_book = Book(
        isbn=book_create.isbn,
        title=book_create.title,
        author=book_create.author,
        publisher=book_create.publisher,
        publish_date=book_create.publish_date,
        category=book_create.category,
        keywords=book_create.keywords,
        description=book_create.description,
        stock=book_create.stock,
        available_stock=book_create.stock
    )
    
    db.add(db_book)
    db.commit()
    db.refresh(db_book)
    
    book_response = BookResponse.from_orm(db_book)
    
    return ResponseModel(
        code=200,
        message="创建图书成功",
        data=book_response
    )

@router.put("/books/{book_id}", response_model=ResponseModel)
async def update_book(
    book_id: int,
    book_update: BookCreate,
    current_admin: User = Depends(get_current_admin_user),
    db: Session = Depends(get_db)
):
    """更新图书"""
    # 查找图书
    db_book = db.query(Book).filter(Book.id == book_id).first()
    if not db_book:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="图书不存在"
        )
    
    # 检查ISBN是否已被其他图书使用
    existing_book = db.query(Book).filter(
        Book.isbn == book_update.isbn,
        Book.id != book_id
    ).first()
    if existing_book:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="ISBN已存在"
        )
    
    # 更新图书信息
    db_book.isbn = book_update.isbn
    db_book.title = book_update.title
    db_book.author = book_update.author
    db_book.publisher = book_update.publisher
    db_book.publish_date = book_update.publish_date
    db_book.category = book_update.category
    db_book.keywords = book_update.keywords
    db_book.description = book_update.description
    
    # 更新库存（保持可用库存的比例）
    if db_book.stock > 0:
        ratio = db_book.available_stock / db_book.stock
        db_book.stock = book_update.stock
        db_book.available_stock = int(book_update.stock * ratio)
    else:
        db_book.stock = book_update.stock
        db_book.available_stock = book_update.stock
    
    db.commit()
    db.refresh(db_book)
    
    book_response = BookResponse.from_orm(db_book)
    
    return ResponseModel(
        code=200,
        message="更新图书成功",
        data=book_response
    )

@router.delete("/books/{book_id}", response_model=ResponseModel)
async def delete_book(
    book_id: int,
    current_admin: User = Depends(get_current_admin_user),
    db: Session = Depends(get_db)
):
    """删除图书"""
    # 查找图书
    db_book = db.query(Book).filter(Book.id == book_id).first()
    if not db_book:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="图书不存在"
        )
    
    # 软删除：设置为不活跃状态
    db_book.is_active = False
    db.commit()
    
    return ResponseModel(
        code=200,
        message="删除图书成功"
    )